//
//  StatusPictureView.m
//  kuangjia
//
//  Created by 张帅 on 15/10/3.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#import "StatusPictureView.h"
#import "UILabel+Contenlable.h"
#import <UIImageView+WebCache.h>
#import <SDWebImageManager.h>
@interface StatusPictureView()<UICollectionViewDataSource,UICollectionViewDelegate>


@end
@implementation StatusPictureView


 static  NSString * HMStatusPictureViewCellID =@"HMStatusPictureViewCellID";

-(void)setStatusViewModel:(StatusViewModel *)statusViewModel{
    _statusViewModel=statusViewModel;
   
    [self sizeToFit];
    
    [self reloadData];
}

-(instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout{

    if (self==[super initWithFrame:frame collectionViewLayout:[[UICollectionViewFlowLayout alloc] init]]) {
       
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        
        layout.minimumInteritemSpacing = HMStatusPictureItemMargin;
        layout.minimumLineSpacing = HMStatusPictureItemMargin;

      [self setBackgroundColor:[UIColor colorWithWhite:0.88 alpha:1]];
        
        self.dataSource =self;
        self.delegate=self;
        
        [self registerClass:[StatusPictureViewCell class] forCellWithReuseIdentifier:HMStatusPictureViewCellID];
    }
    return self;
}


-(CGSize)sizeThatFits:(CGSize)size{
    
    return [self calcViewSize];
}

-(CGSize)calcViewSize{

    
    UICollectionViewFlowLayout* layout = (UICollectionViewFlowLayout*)self.collectionViewLayout;
    
    layout.itemSize = CGSizeMake(HMStatusPictureItemWidth, HMStatusPictureItemWidth);

    // 2. 根据图片数量来计算大小

    NSInteger count = self.statusViewModel.thumbnailURLs.count;
    if (count==0) {
        return CGSizeZero;
    }
    if (count==1) {
        
        CGSize size =CGSizeMake(150, 150);
    // 判断图片是否已经被正确的缓存 Key 是 URL 的完整字符串
        NSString *key = [self.statusViewModel.thumbnailURLs[0]absoluteString];
         // 如果有缓存图片，记录当前图片的大小
       
        UIImage *image =  [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:key];
        if (image) {
            
            size=image.size;
        }
        
        // 单独处理过宽或者过窄的图片
        
        size.width = size.width<40 ?40:size.width;
        
        size.width = size.width > 300? 300 :size.width;
        
        layout.itemSize = size;
        return size;
    }
    // 3> 4张图 2 * 2

    if (count==4) {
        CGFloat  w = (HMStatusPictureItemWidth +HMStatusPictureItemMargin)*2;
        return CGSizeMake(w, w);
    }
    
    // 4> 其他
    /**
     2, 3,
     5, 6,
     7, 8, 9
     */
    NSInteger row =  (count-1) /HMStatusPictureMaxCount +1;
    
    CGFloat h = row *HMStatusPictureItemWidth + (row-1)*HMStatusPictureItemMargin;
    
    CGFloat w = HMStatusPictureMaxWidth;
    
    return CGSizeMake(w, h);
}



-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

    return self.statusViewModel.thumbnailURLs.count;
    
}


-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    StatusPictureViewCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:HMStatusPictureViewCellID forIndexPath:indexPath];
    
    cell.imageURL =self.statusViewModel.thumbnailURLs[indexPath.item];
    
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
 
    [[NSNotificationCenter defaultCenter] postNotificationName:HMStatusPictureViewSelectedPhotoNotification object:self userInfo:@{HMStatusPictureViewSelectedPhotoIndexPathKey: indexPath,HMStatusPictureViewSelectedPhotoURLsKey:self.statusViewModel.bmiddleURLs}];

}


 /// 返回指定 indexPath 对应 cell 在屏幕上的坐标位置
-(CGRect)screenRect:(NSIndexPath*)indexPath{


    StatusPictureViewCell *cell = (StatusPictureViewCell*)[self cellForItemAtIndexPath:indexPath];
    
    return  [self convertRect:cell.frame toCoordinateSpace:[UIApplication sharedApplication].keyWindow];
    
}

-(CGRect)fullScreenRect:(NSIndexPath*)indexPath{
    // 根据［缩略图］`图片`来计算目标尺寸
    // 1. 拿到缩略图
    
    NSString *key =[self.statusViewModel.thumbnailURLs[indexPath.item] absoluteString];
    
    UIImage *image =[[[SDWebImageManager sharedManager]imageCache] imageFromDiskCacheForKey:key];
    
    CGFloat scale  = image.size.height*1.0/image.size.width;
    
    CGFloat w=   [UIScreen mainScreen].bounds.size.width;
    CGFloat h = scale*w;
    
    CGFloat y= ([UIScreen mainScreen].bounds.size.height- h)*0.5;
    if (y <0) {
        y=0;
    }
    
    
    return CGRectMake(0, y, w, h);
}

@end


@interface StatusPictureViewCell()

@property(nonatomic,strong) UIImageView *iconView;
@property(nonatomic,strong) UIImageView *gifIconView;

@end

@implementation StatusPictureViewCell

-(void)setImageURL:(NSURL *)imageURL{
    _imageURL=imageURL;
    [self.iconView sd_setImageWithURL:imageURL];
    
    // 在设置图像 URL 的同时，根据图片的扩展名来判断是否是GIF
    
    
    NSString * string =self.imageURL.absoluteString;
self.gifIconView.hidden = ![string.pathExtension.lowercaseString isEqualToString:@"gif"];
    

    
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        
        [self setupUI];
    }
    return self;
}


-(instancetype)initWithCoder:(NSCoder *)aDecoder{

    if (self==[super initWithCoder:aDecoder]) {
        [self setupUI];
    }
    return self;
}
-(void)setupUI{

    
    [self.contentView addSubview:self.iconView];
    
    [self.iconView addSubview:self.gifIconView];
    
    self.iconView.translatesAutoresizingMaskIntoConstraints=NO;
    
    self.gifIconView.translatesAutoresizingMaskIntoConstraints=NO;


    
    //MARK: iconView
    
   [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
     
       make.left.top.bottom.right.equalTo(self.contentView);
   }];
    //MARK: gif View的布局
    

    [self.gifIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self.iconView);

    }];
   
}
-(UIImageView *)iconView{
    if (_iconView==nil) {
        _iconView=[[UIImageView alloc] init];
        
        // 设置填充模式

//        _iconView.contentMode =UIViewContentModeScaleAspectFit;
//        _iconView.clipsToBounds=YES;
//
    }
    return _iconView;
}


-(UIImageView *)gifIconView{

    if (_gifIconView==nil) {
        _gifIconView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"timeline_image_gif"]];
    }
    return _gifIconView;
}

@end